package com.share.auth.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.share.auth.form.LoginBody;
import com.share.auth.form.RegisterBody;
import com.share.auth.service.SysLoginService;
import com.share.common.core.domain.Result;
import com.share.common.core.utils.JwtUtils;
import com.share.common.core.utils.StringUtils;
import com.share.common.security.auth.AuthUtil;
import com.share.common.security.service.TokenService;
import com.share.common.security.utils.SecurityUtils;
import com.share.system.api.model.LoginUser;

import java.util.Map;

/**
 * 用户登录注册登出等操作 controller
 * token 控制
 */
@RestController
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    // 登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginBody form) {
        // 用户登录 校验账号密码
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());

        // 生成token
        Map<String, Object> token = tokenService.createToken(userInfo);

        // 登录成功后 创建登录用户token令牌
        return Result.ok(token);
    }

    // 登出
    @DeleteMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return Result.ok();
    }

    // 刷新token过期时间
    @PostMapping("/refresh")
    public Result<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return Result.ok();
        }
        return Result.ok();
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return Result.ok();
    }
}
